package com.ntd.study.base.thread.communicate;

import cn.hutool.core.lang.Console;

import java.util.concurrent.Exchanger;

/**
 * 线程通信 - 交换
 */
public class DemoExchange {
    // 等待另一个线程调用 exchange 进行数值交换
    private static Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                Console.log("1:" + exchanger.exchange("交换1")); // 阻塞交换
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                Console.log("2:" + exchanger.exchange("交换2"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
